import React, {useEffect, useRef} from 'react';
import {
    App,
    Button,
    Card,
    Col,
    Flex,
    Form,
    Input,
    InputNumber,
    Row,
    Select, Space, Spin,
    Switch,
    Tag
} from "antd";
import LogFactory from "log/LogFactory";
import {UserPageSettingType} from "type/UserPageSetting";
import {requestGet, requestPost} from "util/request";
import {LoginConstant} from "constant/LoginConstant";
import {useAppSelector} from "../../../redux/hook";
import System from "../../../global/System";
import {tagDataSource} from "../../../constant/TagTuple";

const log = LogFactory.getLog("SettingComponent");
const SettingComponent = () => {
    log.debug("SettingComponent render");
    const menuTreeData = useAppSelector(state => state.navigate.menuTreeData) ;

    const waitingRef = useRef<boolean>(false) ;

    const [loading, setLoading] = React.useState<boolean>(false);

    const [syncColor , setSyncColor] = React.useState<{server: string,local: string}>(
        {
            server: "rgba(39,42,30,0.42)",
            local: "rgba(39,42,30,0.42)"
        }
    ) ;

    const [dataType, setDataType] = React.useState<0|1>(1);
    const [form] = Form.useForm<UserPageSettingType>();
    const {message} = App.useApp() ;
    useEffect(() => {
      const config = System.getInstance().getUserConfig() ;
        form.setFieldsValue(config) ;
    }, []);

    const setWaiting = () => {
       waitingRef.current = true ;
       setTimeout(() => {
              waitingRef.current = false ;
       },5000) ;
    } ;

    const onFinish = async (values: UserPageSettingType) => {
        log.debug("onFinish values: ", values);
        if (waitingRef.current) {
            message.info("请勿重复点击同步!") ;
            return ;
        }
        setWaiting() ;
        setLoading(true);
        values.username = localStorage.getItem(LoginConstant.USERNAME) as string ;
        await requestPost<boolean>("/manager/setting/user-page",values).then(res => {
                log.debug("提交修改成功",res) ;
            });
        setSyncColor({...syncColor,server: "#375e0b"}) ;

        message.success("提交修改成功!") ;
        setLoading(false) ;
    };
    const syncDataToLocal = async () => {
        log.debug("同步数据到本地存储");
        const valid = await form.validateFields().then(values => values ) ;
        System.getInstance().writeConfigToLocal(valid) ;
        setSyncColor({...syncColor,local: "#375e0b"}) ;
    };

    const loadServerData = async () => {
        log.debug("从服务器获取配置数据");
        const data = await requestGet<UserPageSettingType>("/manager/setting/user-page/" + localStorage.getItem(LoginConstant.USERNAME)).then(res => res.data) ;
        form.setFieldsValue(data) ;
        setDataType(0) ;
        setSyncColor({...syncColor,server: "#375e0b"}) ;
    };

    return (
        <Card
            title={"系统设置页面"}
        >
            <Flex style={{paddingBottom: "10px"}} justify={"space-between"}>
                <Space>
                    <Tag color={ syncColor.server }>服务器同步</Tag>
                    <Tag color={ syncColor.local }>本地同步</Tag>
                </Space>
                <Space>
                    <h4>数据源:</h4> {tagDataSource[dataType]}
                </Space>

            </Flex>
          <Spin spinning={loading}>
              <Form<UserPageSettingType>
                  form={form}
                  onFinish={onFinish}
              >
                  <Row gutter={16}>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"userPageSize"} label="用户页面"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <InputNumber min={1} addonAfter={"条"} placeholder={"请求输入页面显示数据量"}/>
                          </Form.Item>
                      </Col>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"rolePageSize"} label="角色页面"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <InputNumber min={1} addonAfter={"条"} placeholder={"请求输入页面显示数据量"}/>
                          </Form.Item>
                      </Col>
                  </Row>
                  <Row gutter={16}>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"menuPageSize"} label="菜单页面"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <InputNumber min={1} addonAfter={"条"} placeholder={"请求输入页面显示数据量"}/>
                          </Form.Item>
                      </Col>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"pathPageSize"} label="路径页面"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <InputNumber min={1} addonAfter={"条"} placeholder={"请求输入页面显示数据量"}/>
                          </Form.Item>
                      </Col>
                  </Row>
                  <Row gutter={16}>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"reimbursePageSize"} label="报销记录"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <InputNumber min={1} addonAfter={"条"} placeholder={"请求输入页面显示数据量"}/>
                          </Form.Item>
                      </Col>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"consumePageSize"} label="消费记录"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <InputNumber min={1} addonAfter={"条"} placeholder={"请求输入页面显示数据量"}/>
                          </Form.Item>
                      </Col>
                  </Row>
                  <Row gutter={16}>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"redirectPath"} label="默认跳转"
                                                          rules={[{required: true, message: '此字段必须输入'}]}>
                              <Input placeholder={"请求输入默认跳转页面"}/>
                          </Form.Item>
                      </Col>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> label="默认展开" name={"expandMenuKey"}>
                              <Select
                                  mode="multiple"
                                  allowClear
                                  // style={{ width: '100%' }}
                                  placeholder="Please select"
                                  options={ menuTreeData?.map(e => {
                                      return {label: e.label,value: e.key} ;
                                  }) }
                              ></Select>
                          </Form.Item>
                      </Col>
                  </Row>
                  <Row gutter={16}>
                      <Col span={12}>
                          <Form.Item<UserPageSettingType> name={"addSkip"} label="添加跳转">
                              <Switch checkedChildren="打开" unCheckedChildren="关闭" defaultChecked/>
                          </Form.Item>
                      </Col>
                      <Col span={12}>
                      </Col>
                  </Row>
                  <Row gutter={16}>
                      <Col span={12}>
                          <Form.Item>
                              <Space>
                                  <Button loading={loading} type={"primary"} key={"user-page-submit"} htmlType={"submit"}>同步到服务器</Button>
                                  <Button loading={loading} type={"primary"} key={"user-page-load-server-data"} onClick={ loadServerData }>获取服务器数据</Button>
                              </Space>
                          </Form.Item>
                      </Col>
                      <Col span={12}>
                          <Button key={"user-page-sync"} type={"primary"} onClick={ syncDataToLocal }>同步到本地</Button>
                      </Col>
                  </Row>
              </Form>
          </Spin>
        </Card>
    );
};

export default SettingComponent;